package com.liu.helloworldsecurity.controller;
/**
 * @Author liuShanYang * @Date 2025 06 13 15 26
 **/
import com.liu.helloworldsecurity.entity.LoginRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import com.liu.helloworldsecurity.uitls.JwtTokenUtil;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Map;
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginRequest request) {
        // 1. 认证用户名密码
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        request.getUsername(),
                        request.getPassword()
                )
        );

        // 2. 生成JWT
        String token = jwtTokenUtil.generateToken(authentication);

        // 3. 返回响应
        return ResponseEntity.ok()
                .header(HttpHeaders.AUTHORIZATION, token)
                .body(Map.of(
                        "message", "登录成功",
                        "username", request.getUsername()
                ));
    }


}